package com.agent.web;

import com.agent.dto.GroupCreateDTO;
import com.agent.dto.GroupUpdateDTO;
import com.agent.entity.Friend;
import com.agent.entity.Group;
import com.agent.entity.GroupFriend;
import com.agent.service.FriendService;
import com.agent.service.GroupFriendService;
import com.agent.service.GroupService;
import com.agent.utils.UserContext;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/web/group")
@RequiredArgsConstructor
public class GroupController {

    private final GroupService groupService;
    private final FriendService friendService;
    private final GroupFriendService groupFriendService;

    // 群组名模糊匹配查询群组
    @GetMapping("/search")
    public ResponseEntity<?> searchGroups(@RequestParam("keyword") String keyword) {
        Map<String, Object> resp = new HashMap<>();

        // 模糊匹配群组
        List<Group> groups = groupService.list(new LambdaQueryWrapper<Group>()
                .like(Group::getName, keyword));

        if (groups.isEmpty()) {
            resp.put("code", 0);
            resp.put("msg", "ok");
            resp.put("data", Collections.emptyList());
            return ResponseEntity.ok(resp);
        }

        // 结果封装：groupId, groupName, owner{id,nickname,email}
        List<Map<String, Object>> result = groups.stream().map(g -> {
            Map<String, Object> m = new HashMap<>();
            m.put("groupId", g.getId());
            m.put("groupName", g.getName());
            m.put("descript", g.getDescription());
            return m;
        }).toList();

        resp.put("code", 0);
        resp.put("msg", "ok");
        resp.put("data", result);
        return ResponseEntity.ok(resp);
    }

    // 查询当前用户加入的群组列表
    @GetMapping("/my")
    public ResponseEntity<?> myGroups() {
        Map<String, Object> resp = new HashMap<>();
        Long userId = UserContext.getUserId();

        // 查询群友表中的群友信息（获得群友表的id），第二个参数表示查询不到不抛异常
        Friend me = friendService.getOne(new LambdaQueryWrapper<Friend>().eq(Friend::getUserId, userId), false);
        if (me == null) {
            resp.put("code", 0);
            resp.put("msg", "ok");
            resp.put("data", Collections.emptyList());
            return ResponseEntity.ok(resp);
        }
        // 根据群友表id查询群组
        List<GroupFriend> relations = groupFriendService.list(new LambdaQueryWrapper<GroupFriend>().eq(GroupFriend::getFriendId, me.getId()));
        if (relations.isEmpty()) {
            resp.put("code", 0);
            resp.put("msg", "ok");
            resp.put("data", Collections.emptyList());
            return ResponseEntity.ok(resp);
        }
        // 根据群组id查询群组信息
        List<Long> groupIds = relations.stream().map(GroupFriend::getGroupId).toList();
        List<Group> groups = groupService.list(new LambdaQueryWrapper<Group>().in(Group::getId, groupIds));

        resp.put("code", 0);
        resp.put("msg", "ok");
        resp.put("data", groups);
        return ResponseEntity.ok(resp);
    }

    // 群组名模糊匹配查找群主
    @GetMapping("/search-owner")
    public ResponseEntity<?> searchOwner(@RequestParam("keyword") String keyword) {
        Map<String, Object> resp = new HashMap<>();

        // 模糊匹配群组
        List<Group> groups = groupService.list(new LambdaQueryWrapper<Group>()
                .like(Group::getName, keyword));

        if (groups.isEmpty()) {
            resp.put("code", 0);
            resp.put("msg", "ok");
            resp.put("data", Collections.emptyList());
            return ResponseEntity.ok(resp);
        }

        // 批量查询群主 Friend
        List<Long> ownerIds = groups.stream()
                .map(Group::getFriendId)
                .filter(Objects::nonNull)
                .distinct()
                .toList();
        List<Friend> owners = ownerIds.isEmpty() ? Collections.emptyList() :
                friendService.list(new LambdaQueryWrapper<Friend>().in(Friend::getId, ownerIds));
        Map<Long, Friend> ownerMap = owners.stream().collect(Collectors.toMap(Friend::getId, f -> f));

        // 结果封装：groupId, groupName, owner{id,nickname,email}
        List<Map<String, Object>> result = groups.stream().map(g -> {
            Map<String, Object> m = new HashMap<>();
            m.put("groupId", g.getId());
            m.put("groupName", g.getName());
            Friend o = ownerMap.get(g.getFriendId());
            if (o != null) {
                Map<String, Object> owner = new HashMap<>();
                owner.put("id", o.getId());
                owner.put("nickname", o.getNickname());
                owner.put("email", o.getEmail());
                m.put("owner", owner);
            } else {
                m.put("owner", null);
            }
            return m;
        }).toList();

        resp.put("code", 0);
        resp.put("msg", "ok");
        resp.put("data", result);
        return ResponseEntity.ok(resp);
    }

    // 获取群组详情和群友列表
    @GetMapping("/detail/{groupId}")
    public ResponseEntity<?> groupDetail(@PathVariable("groupId") Long groupId) {
        Map<String, Object> resp = new HashMap<>();
        // 获得群组详详情信息
        Group group = groupService.getById(groupId);
        if (group == null) {
            resp.put("code", 404);
            resp.put("msg", "Group not found");
            return ResponseEntity.status(404).body(resp);
        }
        // 获得群友列表
        List<GroupFriend> relations = groupFriendService.list(new LambdaQueryWrapper<GroupFriend>().eq(GroupFriend::getGroupId, groupId));
        List<Long> friendIds = relations.stream().map(GroupFriend::getFriendId).collect(Collectors.toList());
        List<Friend> members = friendIds.isEmpty() ? Collections.emptyList() : friendService.list(new LambdaQueryWrapper<Friend>().in(Friend::getId, friendIds));

        Map<String, Object> data = new HashMap<>();
        data.put("group", group);
        data.put("members", members);

        resp.put("code", 0);
        resp.put("msg", "ok");
        resp.put("data", data);
        return ResponseEntity.ok(resp);
    }

    // 创建群组（若无 Friend 记录则创建）
    @Transactional
    @PostMapping("/create")
    public ResponseEntity<?> create(@RequestBody GroupCreateDTO req) {
        Map<String, Object> resp = new HashMap<>();
        Long userId = UserContext.getUserId();
        // 群友表中无该用户，则加入
        Friend me = friendService.getOne(new LambdaQueryWrapper<Friend>().eq(Friend::getUserId, userId), false);
        if (me == null) {
//            User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getId, userId));
            me = Friend.builder()
                    .nickname(req.getNickname())
                    .email(req.getEmail())
                    .userId(userId)
                    .joinTime(LocalDateTime.now())
                    .build();
            friendService.save(me);
        }
        // 创建群组
        Group group = Group.builder()
                .name(req.getName())
                .description(req.getDescription())
                .friendId(me.getId()) // 群主
                .build();
        boolean ok = groupService.save(group);
        if (!ok) {
            resp.put("code", 500);
            resp.put("msg", "create group failed");
            return ResponseEntity.ok(resp);
        }

        // 群主加入群组
        GroupFriend gf = GroupFriend.builder().groupId(group.getId()).friendId(me.getId()).build();
        groupFriendService.save(gf);

        resp.put("code", 0);
        resp.put("msg", "ok");
        resp.put("data", group.getId());
        return ResponseEntity.ok(resp);
    }

    // 修改群组（仅群主）
    @PutMapping("/update/{groupId}")
    public ResponseEntity<?> update(@PathVariable("groupId") Long groupId, @RequestBody GroupUpdateDTO req) {
        Map<String, Object> resp = new HashMap<>();
        Long userId = UserContext.getUserId();
        System.out.println("UserId：" + userId);
        // 获取原本的群组信息
        Group group = groupService.getById(groupId);
        if (group == null) {
            resp.put("code", 404);
            resp.put("msg", "Group not found");
            return ResponseEntity.status(404).body(resp);
        }
        // 只有群主可以修改
        Friend me = friendService.getOne(new LambdaQueryWrapper<Friend>().eq(Friend::getUserId, userId), false);
        if (me == null || !Objects.equals(group.getFriendId(), me.getId())) {
            resp.put("code", 403);
            resp.put("msg", "Only owner can update group");
            return ResponseEntity.status(403).body(resp);
        }
        // 修改
        if (req.getName() != null) group.setName(req.getName());
        if (req.getDescription() != null) group.setDescription(req.getDescription());
        boolean ok = groupService.updateById(group);

        resp.put("code", ok ? 0 : 500);
        resp.put("msg", ok ? "ok" : "update failed");
        return ResponseEntity.ok(resp);
    }
}
